package com.zsummer.zero.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadLocal测试
 * atomic类型测试
 * @author zhouyujiang
 *
 */
public class Demo1 {
	
	static class ATask implements Runnable{
		// 线程不安全 （10个线程的最终结果不确定，有可能是10，有可能小于10）
		static int cnt; 
		// 线程安全 (10个线程的最终结果确定，为10)
		static AtomicInteger atomicIntegerCnt = new AtomicInteger(0); 
		// 线程安全 （10个线程结果确定，每个线程的打印结果都为1）
		static ThreadLocal<Integer> localCnt = new ThreadLocal<Integer>(); 
		
		@Override
		public void run() {
			cnt=0;
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cnt++;
			System.out.println("cnt" + Thread.currentThread() + String.valueOf(cnt));
			
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			atomicIntegerCnt.getAndAdd(1);
			System.out.println("atomicIntegerCnt" + Thread.currentThread() + atomicIntegerCnt.get());
			
			localCnt.set(0);
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			localCnt.set(localCnt.get()+1);
			System.out.println("localCnt" + Thread.currentThread() + String.valueOf(localCnt.get()));
			
			
		}
		
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			Thread thread = new Thread(new ATask());
			thread.start();
		}
	}
	
	

}
